/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    stm32f1xx_it.c
  * @brief   Interrupt Service Routines.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under Ultimate Liberty license
  * SLA0044, the "License"; You may not use this file except in compliance with
  * the License. You may obtain a copy of the License at:
  *                             www.st.com/SLA0044
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f1xx_it.h"
#include "FreeRTOS.h"
#include "task.h"
#include "modbus_auto.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include "queue.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */

/* USER CODE END TD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
 
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
uint8_t ac_rx_buff[25];
uint8_t ac_rx_cont;
uint8_t ac_rx_status =0;
uint8_t adc_cont=0;

extern uint8_t init_status;
extern xQueueHandle xQueueRx_pc_uart1;
extern xQueueHandle xQueueRx_bms_uart2;
extern xQueueHandle xQueueRx_ac_uart3;
extern uint16_t temp_v;
extern uint16_t temp_i;
extern uint16_t temp_ii;
//extern uint16_t temp_v2;

extern uint16_t ac_v;
extern uint16_t ac_w;
extern uint16_t ac_i;
extern float ac_v_f;
extern float ac_i_f;
extern float ac_w_f;
extern uint32_t Voltage_Reg,Power_Reg,Voltage_Parameter_Reg,Power_Parameter_Reg,Current_Reg,Current_Parameter_Reg;
uint16_t v_temp[20];
extern float ActivePower,ACVotage,ACCurrent;
uint16_t i_temp[20];
uint16_t max_v1;
uint16_t max_v2;
uint16_t max_i1;
uint16_t max_i2;
uint16_t min_v1;
uint16_t min_v2;
uint16_t min_i1;
uint16_t min_i2;
//extern MB_ProtocolType MB_Detect_Protocol();
uint8_t aaa;
extern uint8_t proto;
extern uint16_t temp_i7[100];
extern uint16_t temp_v7[100];
extern uint16_t aADCxConvertedData[7];
extern float dc_v[13];
extern float dc_i[13];

extern float v_k[13] ;
extern float i_k[13];
extern float i_k_a[13];


extern uint8_t rx_usart1_cnt;
extern uint8_t ModebusTxBuff[200];
extern uint8_t ModebusRxBuff[128];

extern uint8_t rx_usart3_cnt;
extern uint8_t ModebusTxBuff_M[128];
extern uint8_t ModebusRxBuff_M[128];

//extern typedef enum {
//    MB_PROTO_UNKNOWN,
//    MB_PROTO_RTU,
//    MB_PROTO_TCP
//} MB_ProtocolType;

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/

/* USER CODE BEGIN EV */

/* USER CODE END EV */

/******************************************************************************/
/*           Cortex-M3 Processor Interruption and Exception Handlers          */
/******************************************************************************/
/**
  * @brief This function handles Non maskable interrupt.
  */
void NMI_Handler(void)
{
  /* USER CODE BEGIN NonMaskableInt_IRQn 0 */

  /* USER CODE END NonMaskableInt_IRQn 0 */
  /* USER CODE BEGIN NonMaskableInt_IRQn 1 */

  /* USER CODE END NonMaskableInt_IRQn 1 */
}

/**
  * @brief This function handles Hard fault interrupt.
  */
void HardFault_Handler(void)
{
  /* USER CODE BEGIN HardFault_IRQn 0 */

  /* USER CODE END HardFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_HardFault_IRQn 0 */
    /* USER CODE END W1_HardFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Memory management fault.
  */
void MemManage_Handler(void)
{
  /* USER CODE BEGIN MemoryManagement_IRQn 0 */

  /* USER CODE END MemoryManagement_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
    /* USER CODE END W1_MemoryManagement_IRQn 0 */
  }
}

/**
  * @brief This function handles Prefetch fault, memory access fault.
  */
void BusFault_Handler(void)
{
  /* USER CODE BEGIN BusFault_IRQn 0 */

  /* USER CODE END BusFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_BusFault_IRQn 0 */
    /* USER CODE END W1_BusFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Undefined instruction or illegal state.
  */
void UsageFault_Handler(void)
{
  /* USER CODE BEGIN UsageFault_IRQn 0 */

  /* USER CODE END UsageFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_UsageFault_IRQn 0 */
    /* USER CODE END W1_UsageFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Debug monitor.
  */
void DebugMon_Handler(void)
{
  /* USER CODE BEGIN DebugMonitor_IRQn 0 */

  /* USER CODE END DebugMonitor_IRQn 0 */
  /* USER CODE BEGIN DebugMonitor_IRQn 1 */

  /* USER CODE END DebugMonitor_IRQn 1 */
}

/**
  * @brief This function handles System tick timer.
  */
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

  /* USER CODE END SysTick_IRQn 0 */
  HAL_IncTick();
#if (INCLUDE_xTaskGetSchedulerState == 1 )
  if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED)
  {
#endif /* INCLUDE_xTaskGetSchedulerState */
  xPortSysTickHandler();
#if (INCLUDE_xTaskGetSchedulerState == 1 )
  }
#endif /* INCLUDE_xTaskGetSchedulerState */
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32F1xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f1xx.s).                    */
/******************************************************************************/

/**
  * @brief This function handles DMA1 channel1 global interrupt.
  */
void DMA1_Channel1_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel1_IRQn 0 */
		if(LL_DMA_IsActiveFlag_TC1(DMA1) != RESET)
	{
		LL_DMA_ClearFlag_TC1(DMA1);
		//LL_DMA_ClearFlag_TC1(DMA1);
		
  //   temp_v1[adc_cont]= aADCxConvertedData[0];	
//	   temp_v2[adc_cont]= aADCxConvertedData[2];
//		 temp_v3[adc_cont]= aADCxConvertedData[1];	
//	   temp_v4[adc_cont]= aADCxConvertedData[5];
//		 temp_v5[adc_cont]= aADCxConvertedData[7];	
//	   temp_v6[adc_cont]= aADCxConvertedData[9];
	 temp_v7[adc_cont]= aADCxConvertedData[0];
		
	//	 temp_i1[adc_cont]=  aADCxConvertedData[2];
	//	 temp_i2[adc_cont]=  aADCxConvertedData[2];
	//	 temp_i3[adc_cont]=  aADCxConvertedData[5];
//		 temp_i4[adc_cont]=  aADCxConvertedData[6];
//		 temp_i5[adc_cont]=  aADCxConvertedData[14];
//	   temp_i6[adc_cont]=  aADCxConvertedData[8];
		 temp_i7[adc_cont]=  aADCxConvertedData[2];
				
		adc_cont ++;
		if(adc_cont == 100){
		adc_cont = 0;
		}
   }
		// printf("test dma interrupt");

   
  /* USER CODE END DMA1_Channel1_IRQn 0 */

  /* USER CODE BEGIN DMA1_Channel1_IRQn 1 */

  /* USER CODE END DMA1_Channel1_IRQn 1 */
}

/**
  * @brief This function handles DMA1 channel4 global interrupt.
  */
void DMA1_Channel4_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel4_IRQn 0 */
  // 声明外部变量
  extern volatile uint8_t dma_tx_complete;
	
  if(LL_DMA_IsActiveFlag_TC4(DMA1) != RESET)
	{
		// 清除传输完成标志
		LL_DMA_ClearFlag_TC4(DMA1);
		
		// 禁用DMA通道
		LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_4);
		
		// 设置传输完成标志
		dma_tx_complete = 1;
	}

  /* USER CODE END DMA1_Channel4_IRQn 0 */

  /* USER CODE BEGIN DMA1_Channel4_IRQn 1 */

  /* USER CODE END DMA1_Channel4_IRQn 1 */
}

/**
  * @brief This function handles TIM1 update interrupt.
  */
void TIM1_UP_IRQHandler(void)
{
  /* USER CODE BEGIN TIM1_UP_IRQn 0 */
	 if(LL_TIM_IsActiveFlag_UPDATE(TIM1))

   {
     //   LL_USART_TransmitData8(USART1,0xAA);
        LL_TIM_ClearFlag_UPDATE(TIM1);
	    if(rx_usart1_cnt > 0){
	   
	//	LL_USART_TransmitData8(USART1,0x55); 
	 
	   
	//	tx_buff_uart(USART1,ModebusRxBuff,rx_usart1_cnt);
		//rx_usart1_cnt=0;
		 LL_TIM_DisableCounter(TIM1);  
     	
		 // LL_USART_DisableIT_RXNE(USART1); // 不再禁用RXNE中断，因为我们使用IDLE中断
			if(rx_usart1_cnt < 128) {           
            // 超时处理
            if(rx_usart1_cnt >= 6) { // 最小帧长度
			         
                uint8_t result = MB_Detect_Protocol();
                if(result != MB_PROTO_UNKNOWN) {
                    MB_Auto_Process(result);
	//					rx_usart1_cnt = 0; 
                   // 处理完成
                }
				if(result == MB_PROTO_UNKNOWN) {
					rx_usart1_cnt = 0;
		         	// LL_USART_EnableIT_RXNE(USART1); // 不需要重新启用，因为IDLE中断会处理
				}
            }else {            
            rx_usart1_cnt = 0; // 数据长度不足，重置
            // LL_USART_EnableIT_RXNE(USART1); // 不需要重新启用，因为IDLE中断会处理
        }
        } else {            
            rx_usart1_cnt = 0; // 数据过长，重置
            // LL_USART_EnableIT_RXNE(USART1); // 不需要重新启用，因为IDLE中断会处理
        }
		//   MB_ProtocolType MB_Detect_Protocol ( &ModebusRxBuff, rx_usart1_cnt) ;
	   }

   }


   }

	
  /* USER CODE END TIM1_UP_IRQn 0 */
  /* USER CODE BEGIN TIM1_UP_IRQn 1 */

  /* USER CODE END TIM1_UP_IRQn 1 */


/**
  * @brief This function handles TIM3 global interrupt.
  */
void TIM3_IRQHandler(void)
{
  /* USER CODE BEGIN TIM3_IRQn 0 */
	 if(LL_TIM_IsActiveFlag_UPDATE(TIM3))

   {    //LL_USART_TransmitData8(USART1,0xbb);

        LL_TIM_ClearFlag_UPDATE(TIM3);

   }

  /* USER CODE END TIM3_IRQn 0 */
  /* USER CODE BEGIN TIM3_IRQn 1 */

  /* USER CODE END TIM3_IRQn 1 */
}

/**
  * @brief This function handles USART1 global interrupt.
  */
void USART1_IRQHandler(void)
{
  /* USER CODE BEGIN USART1_IRQn 0 */
	
	portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;
	uint8_t cChar;
		if(LL_USART_IsActiveFlag_RXNE(USART1))
	{	
  	cChar = LL_USART_ReceiveData8(USART1);
	// LL_USART_TransmitData8(USART1,cChar);
//		xQueueSendToBackFromISR(xQueueRx_pc_uart1, &cChar, &xHigherPriorityTaskWoken);
//		portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );

		cChar = LL_USART_ReceiveData8(USART1);
	//	 LL_USART_TransmitData8(USART1,cChar);
	//	xQueueSendToBackFromISR(xQueueRx_pc_uart1, &cChar, &xHigherPriorityTaskWoken);
	//	portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
	
	 LL_TIM_SetCounter(TIM1,0);
	 if(rx_usart1_cnt ==0) { LL_TIM_EnableCounter(TIM1); }
	 ModebusRxBuff[rx_usart1_cnt]=cChar;
	 rx_usart1_cnt++;
   
	}
	
	// IDLE中断处理
	if(LL_USART_IsActiveFlag_IDLE(USART1))
	{
		// 清除IDLE标志位的方法：先读SR，再读DR
		LL_USART_ClearFlag_IDLE(USART1);
		cChar = LL_USART_ReceiveData8(USART1);
		
		// 停止TIM1计数器
		LL_TIM_DisableCounter(TIM1);
		
		// 处理接收到的数据
		if(rx_usart1_cnt > 0) {
			// 检查数据长度是否有效
			if(rx_usart1_cnt < 128) {
				// 检测Modbus协议
				uint8_t result = MB_Detect_Protocol();
				if(result != MB_PROTO_UNKNOWN) {
					// 处理有效的Modbus协议
					MB_Auto_Process(result);
					g_lcdData.communicationStatus = 1;	
          com_cont	 = 20;		
				} else {
					// 协议未知，重置计数器
					rx_usart1_cnt = 0;
				}
			} else {
				// 数据过长，重置计数器
				rx_usart1_cnt = 0;
			}
		}
	}
	
  /* USER CODE END USART1_IRQn 0 */
  /* USER CODE BEGIN USART1_IRQn 1 */

  /* USER CODE END USART1_IRQn 1 */
}

/**
  * @brief This function handles USART2 global interrupt.
  */
void USART2_IRQHandler(void)
{
  /* USER CODE BEGIN USART2_IRQn 0 */
	uint8_t cChar;
	uint8_t sum;
	uint8_t i;
	uint8_t cheaksum,time;

			if(LL_USART_IsActiveFlag_RXNE(USART2))
	{	
		
		
		ac_rx_buff[ac_rx_cont] = LL_USART_ReceiveData8(USART2);
//	 LL_USART_TransmitData8(USART1,ac_rx_buff[ac_rx_cont]);
     ac_rx_cont ++;
		 time = 0;
		}
	
	else if(LL_USART_IsActiveFlag_IDLE(USART2)){
	LL_USART_ClearFlag_IDLE(USART2);
		time++;
		
		if(ac_rx_cont==24 ){	
			
			//LL_GPIO_SetOutputPin(GPIOA,AC2_CNT_Pin);//open ACout
			//usrt2_status = 1;
	    //ac_rx_status = 0;
	    sum =0;
			
		 for(i=2;i<23;i++)
		 {
			sum+=ac_rx_buff[i];
		 }
		 cheaksum = (uint8_t) (sum&0xFF);
		 if(cheaksum==ac_rx_buff[23])
		 {
			 Voltage_Parameter_Reg=(uint32_t)ac_rx_buff[2]<<16|(uint32_t)ac_rx_buff[3]<<8|(uint32_t)ac_rx_buff[4];
			 Voltage_Reg=(uint32_t)ac_rx_buff[5]<<16|(uint32_t)ac_rx_buff[6]<<8|(uint32_t)ac_rx_buff[7];	
			 Power_Reg=(uint32_t)ac_rx_buff[17]<<16|(uint32_t)ac_rx_buff[18]<<8|(uint32_t)ac_rx_buff[19];
			 Power_Parameter_Reg=(uint32_t)ac_rx_buff[14]<<16|(uint32_t)ac_rx_buff[15]<<8|(uint32_t)ac_rx_buff[16];	
			 
			 ACVotage=(Voltage_Parameter_Reg*1.88/Voltage_Reg);//?????��?			 
				 
		   ActivePower=Power_Parameter_Reg*1.88/Power_Reg/10;//?��?????	
			 
			 ac_v = (int16_t) ACVotage*100;				 
			 ac_w = (int16_t ) ActivePower;
			 ac_i = (uint16_t ) ((ActivePower/ACVotage)*100.00);				
			 	
		  	ac_rx_status =1;
		  	ac_rx_cont =0;
		  	time = 0;
}
		 }
		else if(time > 100){
	     ac_v = 0;				 
			 ac_w = 0;
			 ac_i = 0;
       time = 0;	
		}
		ac_rx_cont = 0;
    ac_rx_status =0;
	}
	 if(LL_USART_IsActiveFlag_ORE(USART1))

  {

    LL_USART_ClearFlag_ORE(USART1);

  }
	

  /* USER CODE END USART2_IRQn 0 */
  /* USER CODE BEGIN USART2_IRQn 1 */

  /* USER CODE END USART2_IRQn 1 */
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */
